import time
from typing import Union, List

import psutil


def find_process_by_name(name: str):
    pids = psutil.process_iter()
    for pid in pids:
        if (pid.name() == name):
            return Process(pid.pid)


def Get_pid_by_name(name: str) -> List:
    Pids = []
    Programs = psutil.process_iter()
    for Program in Programs:
        if Program.name() == name:
            Pids.append(Program.pid)
    return Pids


class Process:
    def __init__(self, pid: int):
        self.Process = psutil.Process(pid)
        self.pid = pid

    def get_process_name(self) -> str:
        return self.Process.name()

    def get_source_path(self) -> str:
        return self.Process.exe()

    def get_process_cwd(self) -> str:
        return self.Process.cwd()

    def get_process_start_cmd_command(self) -> str:
        return self.Process.cmdline()

    def get_process_parent(self) -> psutil.Process:
        return self.Process.parent()

    def get_process_parent_on_this_obj(self):
        return Process(self.Process.ppid)

    def get_process_children(self) -> Union[list, psutil.Process]:
        return self.Process.children()

    # def get_process_chidren_by_this_obj(self) -> list:
    #     processes = self.get_process_children()
    #     for children in processes:
    #         pass
    # def get_process_status(self) -> int:
    #     '''
    #     running:0

    #     '''
    def get_process_user_name(self) -> str:
        return self.Process.username()

    def get_process_running_time(self) -> dict:
        now = time.time()
        started_time = self.Process.create_time()
        runtime = now - started_time

        # day
        days = runtime = runtime // (60 * 60 * 24)
        # hour
        hours = runtime = runtime // (60 * 60)
        # minute
        minutes = runtime = runtime // 60
        # second
        seconds = runtime
        return {
            'day': days,
            'hour': hours,
            'minute': minutes,
            'second': seconds
        }

    def get_process_memory(self) -> tuple:
        total = psutil.virtual_memory().total
        memory_p = self.Process.memory_info()
        memory_rss, memory_vms = memory_p.rss, memory_p.vms
        return 100 * float(memory_rss) / total, 100 * float(memory_vms) / total

    # def get_process_CPU_use_on_core(self) -> int:
    #     core_num = self.Process.cpu_num() - 1
    #     persent = psutil.cpu_percent(percpu=1, interval=1)[core_num]
    #     return persent
    def get_thread_num(self) -> int:
        return self.Process.num_threads()

    def get_process_open_file_num(self) -> int:
        return len(self.Process.open_files())

    def get_process_connection(self):
        connections = self.Process.connections()
        return connections
